﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;
using System.Linq;

using FluentValidation;
using FluentValidation.Results;

using Patterns.Collections;

namespace Patterns.Inversion
{
	/// <summary>
	/// Provides access to service registration and retrieval components.
	/// </summary>
	public static class InversionProvider
	{
		private const string _registryTypeNameFormat = "Patterns.Inversion.{0}.{0}ServiceRegistry, Patterns.Inversion.{0}";

		private static readonly IDictionary<string, Func<IServiceRegistry>> _loaders 
			= CreateLoaders("Autofac", "CastleWindsor", "LinFu", "Mef", "Ninject", "Spring", "StructureMap", "Unity");

		/// <summary>
		/// Creates the registry.
		/// </summary>
		/// <param name="container">The container.</param>
		/// <returns></returns>
		public static IServiceRegistry CreateRegistry(string container = null)
		{
			container = container ?? InversionSettings.Current.ContainerName;
			if (string.IsNullOrEmpty(container)) return null;
			Func<IServiceRegistry> loader = _loaders.GetValue(container);
			return loader == null ? null : loader();
		}

		private static IDictionary<string, Func<IServiceRegistry>> CreateLoaders(params string[] containers)
		{
			return containers.Select(container => new
			{
				Name = container,
				Loader = new Func<IServiceRegistry>(() => CreateServiceRegistry(container))
			}).ToDictionary(item => item.Name, item => item.Loader);
		}

		private static IServiceRegistry CreateServiceRegistry(string container)
		{
			var context = new ServiceProviderContext
			{
				ContainerName = container,
				TypeName = string.Format(_registryTypeNameFormat, container)
			};

			ValidationResult result = new ServiceProviderValidator().Validate(context);
			if (!result.IsValid) throw new ValidationException(result.Errors);

			return Activator.CreateInstance(context.ValidatedRegistryType) as IServiceRegistry;
		}
	}
}